package com.spice.im;

import java.util.concurrent.ExecutorService;



import java.util.concurrent.Executors;

//import com.example.android.bitmapfun.util.AsyncTask;
//import com.speed.im.utils.AsyncTask;
//import com.speed.im.utils.AsyncTask.Status;
//import com.speed.im.SpeedIMApplication;
import com.spice.im.utils.AsyncTask;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.stb.core.test.msg.TestActivity;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.stb.isharemessage.utils.HeaderLayout;
//import com.stb.isharemessage.utils.HeaderLayout.HeaderStyle;

//import de.duenndns.ssl.MemorizingTrustManager;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class LoginanimActivity extends FragmentActivity implements IConnectionStatusCallback{
    private static ExecutorService FULL_TASK_EXECUTOR;  
    
    static {  
        FULL_TASK_EXECUTOR = (ExecutorService) Executors.newCachedThreadPool();  
    }; 

    private static final String TAG = "LoginAnim";
    private static final Intent SERVICE_INTENT = new Intent();
    private static final int RECEIVER_PRIORITY = 50;
    static {
	SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
    }
    
	private HeaderLayout mHeaderLayout;
	private TextView  mProgressStatus;//20130428 jindudonghua
    private final ServiceConnection mServConn = new LoginServiceConnection();
    private IXmppFacade mXmppFacade;
    private AsyncTask<IXmppFacade, Integer, Boolean> mTask;
    private Button mCancelBt;
    private TextView mLoginState;
    private boolean mBinded;
////    private BroadcastReceiver mSslReceiver;
//    private Context mContext;
//    private exPhoneCallListener myPhoneCallListener = null;
//    private TelephonyManager tm = null;
    
    String login;
    String password;
    
    private int fromRegister = 0;//0 false 1 true
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loginanim);
		
		Intent intent = getIntent(); 
	    //0 false 1 true
		fromRegister = intent.getIntExtra("fromRegister", (int) 0); 
		
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
		mHeaderLayout.init(HeaderStyle.DEFAULT_TITLE);
		mHeaderLayout.setDefaultTitle("登录", null);
		mProgressStatus = (TextView)findViewById(R.id.mProgressStatus);
		//取消按钮
		mCancelBt = (Button) findViewById(R.id.loginanim_cancel_button);
		mCancelBt.setOnClickListener(new ClickListener());
		
	    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
	    login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
	    password = settings.getString(BeemApplication.ACCOUNT_PASSWORD_KEY, "");
		
//		mSslReceiver = new BroadcastReceiver() {
//		    public void onReceive(Context ctx, Intent i) {
//			try {
//			    Log.i(TAG, "Interception the SSL notification");
//			    PendingIntent pi = i.getParcelableExtra(MemorizingTrustManager.INTERCEPT_DECISION_INTENT_LAUNCH);
//			    pi.send();
//			    abortBroadcast();
//			} catch (PendingIntent.CanceledException e) {
//			    Log.e(TAG, "Error while displaying the SSL dialog", e);
//			}
//		    }
//		};
//		mContext = this;
//	    IntentFilter mFilter = new IntentFilter();
//	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
//	    registerReceiver(mNetWorkReceiver, mFilter);
//	    
//        /* 添加自己实现的PhoneStateListener */
//        myPhoneCallListener = new exPhoneCallListener();
//       
//       /* 取得电话服务 */
//        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//       
//        /* 注册电话通信Listener */
//        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
        SpiceApplication.getInstance().addActivity(this);
	}
    @Override
    protected void onStart() {
    	super.onStart();
    	if ((mTask!=null && mTask.getStatus() != com.spice.im.utils.AsyncTask.Status.RUNNING) || mTask==null){
    	    mTask = new LoginTask(this);
    	}if (!mBinded)
    	    mBinded = bindService(LoginanimActivity.SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
//    	IntentFilter filter = new IntentFilter(MemorizingTrustManager.INTERCEPT_DECISION_INTENT
//    		+ "/" + getPackageName());
//    	filter.setPriority(RECEIVER_PRIORITY);
//    	registerReceiver(mSslReceiver, filter);
    }
    
    @Override
    protected void onStop() {
		super.onStop();
		if (mBinded && mTask.getStatus() != AsyncTask.Status.RUNNING) {
		    unbindService(mServConn);
		    mXmppFacade = null;
		    mBinded = false;
		}
//		unregisterReceiver(mSslReceiver);
    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
////		clearAsyncTask();
// 	    XmppConnectionAdapter.isPause = true;
//		if(XmppConnectionAdapter.instance!=null)
//			XmppConnectionAdapter.instance.resetApplication();
//		XmppConnectionAdapter.instance = null;
//		stopService(SERVICE_INTENT);
	    try{
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			unbindService(mServConn);
			mXmppFacade = null;
			mBinded = false;
		}
		mXmppFacade = null;
////		unregisterReceiver(mNetWorkReceiver); // 删除广播
////		if(tm!=null){
////			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
////			tm = null;
////		}
////		if(myPhoneCallListener!=null)
////			myPhoneCallListener = null;
//		
//		BeemApplication.getInstance().exit();
////		unregisterReceiver(mSslReceiver);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO use onBackPressed on Eclair (2.0)
		if (keyCode == KeyEvent.KEYCODE_BACK && mTask.getStatus() != AsyncTask.Status.FINISHED) {
		    if (!mTask.cancel(true)) {
			Log.d(TAG, "Can't interrupt the connection");
		    }
		    setResult(Activity.RESULT_CANCELED);
		}
		return super.onKeyDown(keyCode, event);
    }
    
    /**
     * The service connection used to connect to the Beem service.
     */
    private class LoginServiceConnection implements ServiceConnection {

		/**
		 * Constructor.
		 */
		public LoginServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(LoginanimActivity.this);
		    		
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
		    	if (mTask.getStatus() == AsyncTask.Status.PENDING)
				    mTask.executeOnExecutor(FULL_TASK_EXECUTOR,mXmppFacade);
//				    	mTask.executeOnExecutor(FULL_TASK_EXECUTOR);
				    mBinded = true;
		    }
//		    if (mTask.getStatus() == AsyncTask.Status.PENDING)
//		    mTask.executeOnExecutor(FULL_TASK_EXECUTOR,mXmppFacade);
////		    	mTask.executeOnExecutor(FULL_TASK_EXECUTOR);
//		    mBinded = true;
		}
	
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    try{
			    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
			    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
		    }catch (RemoteException e) {
		    	e.printStackTrace();
		    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
    
    /**
     * Click event listener on cancel button.
     */
    private class ClickListener implements OnClickListener {

		/**
		 * Constructor.
		 */
		ClickListener() {
		}
	
		@Override
		public void onClick(View v) {
		    if (v == mCancelBt) {
				if (!mTask.cancel(true)) {
				    Log.d(TAG, "Can't interrupt the connection");
				}
				setResult(Activity.RESULT_CANCELED);
				finish();
		    }
		}
    }
    

    /**
     * Asynchronous class for connection.
     */
    //异步线程方式登录
    private class LoginTask extends LoginAsyncTask {
		/**
		 * Constructor.
		 */
		LoginTask(Context mContext) {
			super.setMContext(mContext);
		}
	
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Boolean result) {
			Log.d("######@@@@@@******LoginaimActivity result******@@@@@@######", "result="+result);
		    if (result == null || !result) { // Task cancelled or exception
			if (!result) {
			    Intent i = new Intent();
			    i.putExtra("message", getErrorMessage());
			    LoginanimActivity.this.setResult(Activity.RESULT_CANCELED, i);
			} else
				LoginanimActivity.this.setResult(Activity.RESULT_CANCELED);
			LoginanimActivity.this.finish();
		    } else {
	//		mCancelBt.setEnabled(false);
		    	LoginanimActivity.this.startService(LoginanimActivity.SERVICE_INTENT);
	//		LoginAnim.this.startService(intent_notificationService);
		    	LoginanimActivity.this.setResult(Activity.RESULT_OK);
		    	if(fromRegister==1){
		    		startActivity(new Intent(LoginanimActivity.this, ContactFrameActivity.class));
		    	}
		    	LoginanimActivity.this.finish();
		    }
		}
	
		@Override
		protected void onProgressUpdate(Integer ... values) {
			mProgressStatus.setText(getResources().getStringArray(R.array.loganim_state)[values[0]]);
		}
	
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onCancelled()
		 */
		@Override
		protected void onCancelled() {
		    super.onCancelled();
			XmppConnectionAdapter.isPause = true;
			XmppConnectionAdapter.isReconnectFlag = false;
			if(XmppConnectionAdapter.instance!=null){
			XmppConnectionAdapter.instance.resetApplication();
			try{
				XmppConnectionAdapter.instance.logoutReconnect();
			} catch (Exception e) {
				    e.printStackTrace();
			}
			}
			XmppConnectionAdapter.instance = null;
		    LoginanimActivity.this.stopService(LoginanimActivity.SERVICE_INTENT);
		}

    }
    
    
    @Override
	public void connectionStatusChanged(int connectedState, String reason) {
		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
		switch (connectedState) {
		case 0://connectionClosed
			mHandler3.sendEmptyMessage(0);
			break;
		case 1://connectionClosedOnError
//			mConnectErrorView.setVisibility(View.VISIBLE);
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接异常!");
			mHandler3.sendEmptyMessage(1);
			break;
		case 2://reconnectingIn
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接中...");
			mHandler3.sendEmptyMessage(2);
			break;
		case 3://reconnectionFailed
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("重连失败!");
			mHandler3.sendEmptyMessage(3);
			break;
		case 4://reconnectionSuccessful
//			mNetErrorView.setVisibility(View.GONE);
			mHandler3.sendEmptyMessage(4);

		default:
			break;
		}
	}
	Handler mHandler3 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;

			case 1:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("连接异常!");
				break;

			case 2:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("连接中...");
				break;
			case 3:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("重连失败!");
				break;
				
			case 4:
//				mNetErrorView.setVisibility(View.GONE);
				String udid = "";
				String partnerid = "";
//				try{
//					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
//					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
//				}catch(Exception e){
//					e.printStackTrace();
//				}
//				udidTextView.setText("udid="+udid);
//				partneridEditText.setText(partnerid);
////				getContactList();//20141025 added by allen
				break;
			case 5:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
				break;
			case 6:
//				if(mXmppFacade!=null 
////						&& mXmppFacade.getXmppConnectionAdapter()!=null 
////						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
////						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
////						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& BeemConnectivity.isConnected(mContext)){
//					
//				}else{
//					mNetErrorView.setVisibility(View.VISIBLE);
//					if(BeemConnectivity.isConnected(mContext))
//					mConnect_status_info.setText("网络可用,连接中...");
//				}
				break;	
			}
		}

	};
//	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();  
//            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
//                Log.d("PoupWindowContactList", "网络状态已经改变");  
////                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
////                info = connectivityManager.getActiveNetworkInfo();    
////                if(info != null && info.isAvailable()) {  
////                    String name = info.getTypeName();  
////                    Log.d(tag, "当前网络名称：" + name);  
////                    //doSomething()  
////                } else {  
////                    Log.d(tag, "没有可用网络");  
////                  //doSomething()  
////                }  
//                if(BeemConnectivity.isConnected(context)){
////                	mNetErrorView.setVisibility(View.GONE);
////                	isconnect = 0;
//                	mHandler3.sendEmptyMessage(6);//4
//                }else{
////                	mNetErrorView.setVisibility(View.VISIBLE);
////                	isconnect = 1;
//                	mHandler3.sendEmptyMessage(5);
//                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
//                }
//            } 
//        }
//	};
//	
//	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
//    /* 内部class继承PhoneStateListener */
//    public class exPhoneCallListener extends PhoneStateListener
//    {
//        /* 重写onCallStateChanged
//        当状态改变时改变myTextView1的文字及颜色 */
//        public void onCallStateChanged(int state, String incomingNumber)
//        {
//          switch (state)
//          {
//            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
//            case TelephonyManager.CALL_STATE_IDLE:
//            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
//            	if(phonestate){
//            		onPhoneStateResume();
//            	}
//            	phonestate = false;
//              break;
//            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
//            case TelephonyManager.CALL_STATE_OFFHOOK:
//            	Log.e("================20131216 接起电话时================", "接起电话时");
//            	onPhoneStatePause();
//            	phonestate = true;
//              break;
//            /* 电话进来时 :在通话的过程中*/
//            case TelephonyManager.CALL_STATE_RINGING:
////              getContactPeople(incomingNumber);
//            	Log.e("================20131216 电话进来时================", "电话进来时");
////            	onBackPressed();
//            	onPhoneStatePause();
//            	phonestate = true;
//              break;
//            default:
//              break;
//          }
//          super.onCallStateChanged(state, incomingNumber);
//        }
//    }
//    
//    protected void onPhoneStatePause() {
////		super.onPause();
//    	try{
//
//		if (mBinded) {
//			getApplicationContext().unbindService(mServConn);
//		    mBinded = false;
//		}
////		mXmppFacade = null;
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
//    }
//    
//    protected void onPhoneStateResume() {
////		super.onResume();
//    	try{
//		if (!mBinded){
////		    new Thread()
////		    {
////		        @Override
////		        public void run()
////		        {
//		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
//
////		        }
////		    }.start();		    
//		}
//		if (mBinded){
//
//		}
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
//    }
}
